package com.example.exercise.excel.controller;

import com.example.exercise.common.base.BaseResponse;
import com.example.exercise.excel.service.ExcelService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.stream.FileImageOutputStream;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
class ExcelController {
    @Resource
    private ExcelService excelService;

    @RequestMapping(value = "output/{type}",method = RequestMethod.GET)
    public void outputExcel(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, @PathVariable("type") int type) {
        int size = 100;
        List<HashMap<String,Object>> list = new ArrayList<>(size);
        for (int i = 0; i < size; i++) {
            HashMap<String,Object> map = new HashMap<>();
            map.put("name","用户" + i);
            map.put("sex",new Random().nextInt(2));
            map.put("income",i*1000);
            list.add(map);
        }

        String fileName = "导出用户信息明细"+ new SimpleDateFormat("yyyyMMdd").format(System.currentTimeMillis());
        String[] heads = {"姓名","性别","月收入"};
        String[] cols = {"name","sex","income"};
        String[] numerics = {"sex","income"};//数字对应的列
        excelService.outputExcel(type,httpServletRequest,httpServletResponse,list,fileName,heads,cols,numerics);
    }

    @RequestMapping(value = "upload/{type}",method = RequestMethod.POST)
    @ResponseBody
    public BaseResponse<List<Map<String, Object>>> uploadExcel(@RequestParam("file") MultipartFile multipartFile,
                                                               @PathVariable("type") int type,
                                                               @RequestParam("cols") String cols) {
        String[] colIndexs = cols.split(",");
        Integer[] mapIndex = new Integer[colIndexs.length];
        for (int i = 0; i < colIndexs.length; i++) {
            mapIndex[i] = Integer.valueOf(colIndexs[i]);
        }

        List<Map<String, Object>> list = excelService.uploadExcel(multipartFile,type,mapIndex);
        BaseResponse<List<Map<String, Object>>> baseResponse = new BaseResponse<>();
        if(list.size() > 0){
            baseResponse.ok(list);
        }else{
            baseResponse.setMsg("请求数据为空");
            baseResponse.setCode(-3);
        }
        return baseResponse;
    }

    @RequestMapping(value = "uploadAllColumn/{type}",method = {RequestMethod.POST},produces = { MediaType.APPLICATION_JSON_VALUE})
    @ResponseBody
    public BaseResponse<List<Map<String, Object>>> uploadExcelAllColumn(@RequestParam("file") MultipartFile multipartFile, @PathVariable("type") int type) {

        List<Map<String, Object>> list = excelService.uploadExcelAll(multipartFile,type);
        BaseResponse<List<Map<String, Object>>> baseResponse = new BaseResponse<>();
        if(list.size() > 0){
            baseResponse.ok(list);
        }else{
            baseResponse.setCode(-3);
            baseResponse.setMsg("请求数据为空");
        }
        return baseResponse;
    }

    @RequestMapping(value = "ddPicFromExcel",method = RequestMethod.POST)
    @ResponseBody
    public BaseResponse<Object> dpicForDD(@RequestParam("file") MultipartFile multipartFile) {
        RestTemplate restTemplate = new RestTemplate();
        BaseResponse<Object> baseResponse = new BaseResponse<>();
        List<Map<String, Object>> list = excelService.uploadExcel(multipartFile,0, new Integer[]{5,7});
        String urlFinal = "";
        try{
            for (int i = 0; i < list.size(); i++) {
                Map<String, Object> map = list.get(i);
                String dateString = String.valueOf(map.get("col5"));
                String url = String.valueOf(map.get("col7"));
                String suffix = "";
                if(i > 0){
                    Map<String, Object> map1 = list.get(i - 1);
                    if(String.valueOf(map1.get("col5")).equals(dateString)){
                        suffix = "下午";
                    }
                }
                if(i < list.size() - 1){
                    Map<String, Object> map1 = list.get(i + 1);
                    if(String.valueOf(map1.get("col5")).equals(dateString)){
                        suffix = "上午";
                    }
                }
                File file = new File("D://远程办公截图/史文康");
                if(!file.exists() || !file.isDirectory()){
                    file.mkdirs();
                }
                String path = "D://远程办公截图/史文康/"+dateString + suffix + ".jpg";
                url = url.replace(";","").replaceAll("\n","");
                ResponseEntity<byte[]> responseEntity = restTemplate
                        .exchange(url, HttpMethod.GET, null, byte[].class);
                byte[] bytes = responseEntity.getBody();

                FileImageOutputStream imageOutput = new FileImageOutputStream(new File(path));
                imageOutput.write(bytes, 0, bytes.length);
                imageOutput.close();
                urlFinal = url;
            }
            baseResponse.setCode(0);
            baseResponse.setMsg("下载图片成功，请在路径：D://远程办公截图666/ 下查看，最后一张成功的图片的url是：" + urlFinal);
        } catch(Exception ex) {
            baseResponse.setCode(-3);
            baseResponse.setMsg("error: " + ex.getMessage());
            ex.printStackTrace();
        }
        return baseResponse;
    }

    @RequestMapping(value = "picForDdUser",method = RequestMethod.POST)
    @ResponseBody
    public BaseResponse<Object> dpicForDDUser(@RequestParam("file") MultipartFile multipartFile,@RequestParam("name") String name) {
        RestTemplate restTemplate = new RestTemplate();
        BaseResponse<Object> baseResponse = new BaseResponse<>();
        List<Map<String, Object>> list = excelService.uploadExcel(multipartFile,0, new Integer[]{1,5,7});
        String urlFinal = "";
        List<Map<String, Object>> listNew = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            Map<String, Object> map = list.get(i);
            if(map.get("col1").equals(name)){
                listNew.add(map);
            }
        }
        try{
            for (int i = 0; i < listNew.size(); i++) {
                Map<String, Object> map = listNew.get(i);
                String dateString = String.valueOf(map.get("col5"));
                String url = String.valueOf(map.get("col7"));
                String suffix = "";
                if(i > 0){
                    Map<String, Object> map1 = listNew.get(i - 1);
                    if(String.valueOf(map1.get("col5")).equals(dateString)){
                        suffix = "上午";
                    }
                }
                if(i < listNew.size() - 1){
                    Map<String, Object> map1 = listNew.get(i + 1);
                    if(String.valueOf(map1.get("col5")).equals(dateString)){
                        suffix = "下午";
                    }
                }
                String dirString = "D://远程办公截图/" +name;
                File file = new File(dirString);
                if(!file.exists() || !file.isDirectory()){
                    file.mkdirs();
                }
                String path = dirString+ "/" +dateString.replace("-",".") + "-" + suffix + ".jpg";
                url = url.replace(";","");
                ResponseEntity<byte[]> responseEntity = restTemplate
                        .exchange(url, HttpMethod.GET, null, byte[].class);
                byte[] bytes = responseEntity.getBody();

                FileImageOutputStream imageOutput = new FileImageOutputStream(new File(path));
                imageOutput.write(bytes, 0, bytes.length);
                imageOutput.close();
                urlFinal = url;
            }
            baseResponse.setCode(0);
            baseResponse.setMsg("下载图片成功，请在路径：D://远程办公截图/ 下查看，最后一张成功的图片的url是：" + urlFinal);
        } catch(Exception ex) {
            baseResponse.setCode(-3);
            baseResponse.setMsg("error: " + ex.getMessage());
            ex.printStackTrace();
        }
        return baseResponse;
    }
}
